<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               :row-class-name="rowClassName"
               :cell-class-name="rowClassName"
               @on-load="onLoad">
      <template #menu-left>
        <el-button
                type="primary"
                icon="el-icon-plus"
                v-if="permission.stock_out_main_add"
                @click="handleAdd"
        >新增
        </el-button>
        <!--<el-button type="danger"-->
                   <!--icon="el-icon-delete"-->
                   <!--v-if="permission.stock_out_main_delete"-->
                   <!--@click="handleDelete">删 除-->
        <!--</el-button>-->
      </template>
      <template #outDate-search="{ disabled, size }">
        <!--<div style="display: flex;flex-direction: start;">-->
          <!--<el-select v-model="query.stockDateRule" placeholder="比较" filterable clearable>-->
            <!--<el-option label="" value=""></el-option>-->
            <!--<el-option value=">" label="大于">大于</el-option>-->
            <!--<el-option value=">=" label="大于等于">大于等于</el-option>-->
            <!--<el-option value="=" label="等于">等于</el-option>-->
            <!--<el-option value="!=" label="不等于">不等于</el-option>-->
            <!--<el-option value="<=" label="小于等于">小于等于</el-option>-->
            <!--<el-option value="<" label="小于">小于</el-option>-->
          <!--</el-select>-->
          <!--<el-date-picker-->
                  <!--size="default"-->
                  <!--v-model="query.stockDateSearch"-->
                  <!--type="date"-->
                  <!--:format="dateFormat"-->
                  <!--:value-format="dateFormat"-->
                  <!--:unlink-panels="true"-->
                  <!--clearable-->
                  <!--placeholder="出仓日期"-->
                  <!--:picker-options="pickerOptions"-->
          <!--&gt;-->
          <!--</el-date-picker>-->
        <!--</div>-->
        <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.stockDateRange"
                type="daterange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="出仓日期"
                @change="handleDatePickerChange"
                :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>
      <template #menu="{ row, size, type }">
        <el-tooltip content="查看" placement="top">
          <el-button
                  icon="el-icon-view"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleView(row)"
                  v-if="permission.stock_out_main_view"
          >
          </el-button>
        </el-tooltip>
        <!--<el-tooltip content="修改" placement="top"  v-if="row.outStatus =='draft'">-->
          <!--<el-button-->
                  <!--icon="el-icon-edit"-->
                  <!--link-->
                  <!--:size="size"-->
                  <!--:type="type"-->
                  <!--@click="() => handleEdit(row)"-->
                  <!--v-if="permission.stock_out_main_edit"-->
          <!--&gt;-->
          <!--</el-button>-->
        <!--</el-tooltip>-->
        <el-tooltip content="确认单据" placement="top" v-if="row.outStatus =='draft' && row.fromDept ===  this.deptId && row.outType !=='调拨出仓'">
          <el-button
                  icon="Pointer"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleEdit(row)"
                  v-if="permission.stock_out_main_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="反审核" placement="top" v-if="row.outStatus !='draft' && row.fromDept ===  this.deptId && row.outType !=='调拨出仓' && row.isUsed!=='是' && row.invoiced!=='是'">
          <el-button
                  icon="Stamp"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleReject(row)"
                  v-if="permission.stock_out_main_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="快速入仓" placement="top" v-if="this.isRole === 1 && row.toDept === this.deptId && row.outType ==='生产出仓' && row.outStatus ==='confirmed' && row.isUsed!=='是'">
          <el-button
                  icon="el-icon-download"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleGenStockIn(row)"
                  v-if="permission.stock_out_main_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="生成发票" placement="top" v-if="this.isRole === 1  && row.outType ==='销售出仓' && row.outStatus ==='confirmed' && row.invoiced!=='是'">
          <el-button
                  icon="el-icon-download"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleGenInvoice(row)"
                  v-if="permission.stock_out_main_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="出仓单报表" placement="top" >
          <el-button
                  icon="Reading"
                  link
                  :size="size"
                  :type="type"
                  @click="() => showChoice(row)"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top" v-if="row.outStatus =='draft'&& row.fromDept ===  this.deptId && row.outType !=='调拨出仓'">
          <el-button
                  icon="el-icon-delete"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rowDel(row)"
                  v-if="permission.stock_out_main_delete"
          >
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <stock-out-form ref="StockOutForm" @success="refreshChange"></stock-out-form>
    <gen-stock-in ref="GenStockIn" @success="skipStockIn"></gen-stock-in>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, reject,checkStockOut,stockOutReport,genInvoice} from "@/api/anwise/stock/stock_out_main";
  import {mapGetters} from "vuex";
  import StockOutForm from "./components/stock_out_form.vue";
  import {userCompany} from "@/api/anwise/common";
  import GenStockIn from "./components/gen_stock_in.vue";
  import {getDictionary} from "@/api/system/dictbiz";

  export default {
    components: {
      StockOutForm,
      GenStockIn
    },
    data() {
      return {
        form: {},
        query: {},
          stockDateRange:[],
          search:{},
          pickerOptions: {},
        loading: true,
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        dateFormat: 'YYYY-MM-DD',
        isRole:"",
        deptId:"",
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: true,
          reserveSelection:true,
          labelWidth: 150,
          searchLabelWidth:100,
          indexWidth:100,
          menuWidth: 210,
          addBtn: false,
          editBtn: false,
          viewBtn: false,
          delBtn: false,
          stripe: true,
          searchIndex: 3,
          searchIcon: false,
          searchEnter:true,
          column: [
            {
              label: "出仓单号",
              prop: "idNo",
              type: "input",
              search: true,
              width:180,
              overHidden: true,
              sortable: true,
              rules: [{
                required: true,
                message: "请输入出仓单号",
                trigger: "blur"
              }],
            },
              {
                  label: "出仓日期",
                  prop: "outDate",
                  width:140,
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  search: true,
              },
              {
                  label: "物流单号",
                  prop: "logisticsNo",
                  width:140,
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  search: true,
              },
            {
              label: "所属机构",
              prop: "fromName",
              width:160,
              type: "input",
              overHidden: true,
              sortable: true,
              search: true,
            },
            {
              label: "收款方",
              prop: "companyName",
              width:160,
              type: "input",
                search:true,
              overHidden: true,
              sortable: true,
            },
            {
              label: "收货单位编号",
              prop: "toNo",
              width:160,
              type: "number",
              controls: false,
              overHidden: true,
              search: true,
              sortable: true,
            },
            {
              label: "收货单位名称",
              prop: "toName",
              width:160,
              type: "input",
              overHidden: true,
              search: true,
              sortable: true,
            },
            {
              label: "出仓类型",
              prop: "outType",
              width:120,
              type: "select",
              dicUrl: "/blade-system/dict-biz/dictionary?code=out_type",
              // dicData:[],
              filterable: true,
              clearable:false,
              props: {
                label: 'dictValue',
                value: 'dictKey',
              },
              dataType: 'string',
              overHidden: true,
              sortable: true,
              search: true,
            },
            {
              label: "交货方式",
              prop: "deliMeth",
              width:120,
              type: "input",
              overHidden: true,
              sortable: true,
            },
            {
              label: "交货地址",
              prop: "deliAddr",
              width:160,
              type: "input",
              overHidden: true,
              sortable: true,
            },
            // {
            //   label: "结算方式",
            //   prop: "payType",
            //   width:120,
            //   type: "input",
            //   overHidden: true,
            //   sortable: true,
            // },
            {
              label: "销售方式",
              prop: "salesType",
              width:120,
              type: "input",
              overHidden: true,
              sortable: true,
            },
            {
              label: "币别",
              prop: "rmb",
              width:100,
              type: "input",
              overHidden: true,
              sortable: true,
            },
            {
              label: "出仓备注",
              prop: "remark",
              width:160,
              type: "input",
              overHidden: true,
              sortable: true,
            },
              {
                  label: "已开发票",
                  prop: "invoiced",
                  width:120,
                  type: "select",
                  dicUrl: "/blade-system/dict-biz/dictionary?code=biz_yes_no",
                  // dicData:[],
                  filterable: true,
                  clearable:false,
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  overHidden: true,
                  sortable: true,
                  search: true,
                  formatter:(row,value,label)=>{
                      if (row.outType !== '销售出仓') {
                          return '';
                      } else {
                          return value;
                      }
                  }
              },
            {
              label: "创建人",
              prop: "createUserName",
              width:120,
              type: "input",
              overHidden: true,
              sortable: true,
            },
            // {
            //   label: "创建部门",
            //   prop: "createDept",
            //   type: "input",
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   hide: true,
            // },
            {
              label: "创建时间",
              prop: "createTime",
              width:120,
              type: "input",
              overHidden: true,
              sortable: true,
            },
            // {
            //   label: "修改人",
            //   prop: "updateUser",
            //   type: "input",
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   hide: true,
            // },
            // {
            //   label: "修改时间",
            //   prop: "updateTime",
            //   type: "input",
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   hide: true,
            // },
            // {
            //   label: "状态",
            //   prop: "status",
            //   type: "input",
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   hide: true,
            // },
            // {
            //   label: "是否已删除",
            //   prop: "isDeleted",
            //   type: "input",
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   hide: true,
            // },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.stock_out_main_add, false),
          viewBtn: this.validData(this.permission.stock_out_main_view, false),
          delBtn: this.validData(this.permission.stock_out_main_delete, false),
          editBtn: this.validData(this.permission.stock_out_main_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      this.init();
    },
    methods: {
        handleGenInvoice(row) {
          genInvoice(row.id).then(res=>{
            if (res.data.success) {
                this.onLoad(this.page);
                this.$message({
                type: "success",
                message: res.data.msg ||"操作成功!"
              });
            }
          })
        },
        showChoice(row){
          stockOutReport(row.id, this.isEnglish,this.hiddenBom).then(res => {
            if(res.data.success) {
              const file = res.data.data;
              // const originUrl = (file.url.replace(file.domain, `${this.res}/`));
              const url = file.url;
              // this.$refs.preview.open({
              //     url: url || "",
              //     originUrl: originUrl || ""
              // });
              console.log(url)
              window.open(`/plugins/pdfjs/web/viewer.html?file=`+url);
            }
          })
        },
        handleReject(row) {
            this.loading = true;
            checkStockOut(row.id).then(res=>{
                this.loading = false;
              if (res.data.success) {
                reject(row.id).then((res) => {
                  if (res.data.success) {
                    this.onLoad(this.page);
                    this.$message({
                      type: "success",
                      message: res.data.msg ||"操作成功!"
                    });
                  }
                });
              }
            }).catch(() => {
                this.loading = false;
            });
        },
        rowClassName({row, rowindex}) {
            if (row.outStatus ==='draft') {
                return 'row-yellow';
            }
        },
      init(){
        userCompany().then(res=>{
          if (res.data.success) {
            this.dept = res.data.data;
            if (!this.dept) {
              this.$message({
                type: "error",
                message: "用户无组织机构信息，请联系安伟工作人员！"
              });
              return;
            } else {
              this.isRole = this.dept.bodyType;
              if(this.isRole !== 1){
                this.findObject(this.option.column, 'fromName').search = false;
              }
              this.deptId = this.dept.id;
            }
          }
        })
        // getDictionary({code:"out_type"}).then(res=>{
        //   let dataDic = res.data.data;
        //   dataDic = dataDic.filter(function(item) {
        //     return item.dictValue !== "调拨出仓";
        //   });
        //   // if(this.isRole === 1){
        //   //   dataDic.forEach(item=>{
        //   //     if(item.dictValue !== "退料出仓" && item.dictValue !== "生产出仓"){
        //   //       this.outTypeDic.push(item);
        //   //     }
        //   //   })
        //   // }else if(this.isRole === 3){
        //   //   dataDic.forEach(item=>{
        //   //     if(item.dictValue !== "退货出仓" && item.dictValue !== "销售出仓"){
        //   //       this.outTypeDic.push(item);
        //   //     }
        //   //   })
        //   // }
        //   this.findObject(this.option.column, 'outType').dicData = dataDic;
        // })
      },
      skipStockIn(){
        this.$router.push("/anwise/stock/stock_in_main");
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleGenStockIn(row){
          checkStockOut(row.id).then(res=> {
              this.loading = false;
              if (res.data.success) {
                  let title = "快速入仓";
                  let type = 'add';
                  const outId = row.id;
                  this.$refs.GenStockIn.show({
                      outId,
                      title,
                      type
                  })
              }
          }).catch(() => {
              this.loading = false;
          });
      },
      handleView(row) {
        let title="查看出仓单信息";
        let type='view';
        const id = row.id;
        this.$refs.StockOutForm.show({
          id,
          title,
          type
        })
      },
      handleEdit(row) {
            if (row.billCheck =='是') {
                this.$message({
                    type: "error",
                    message: " 该出仓单已对账，不允许编辑！"
                });
                return;
            }
        let title="出仓单信息";
        let type='edit';
        const id = row.id;
        this.$refs.StockOutForm.show({
          id,
          title,
          type
        })
      },
      handleAdd(){
        userCompany().then(res => {
          if (res.data.success) {
            this.dept = res.data.data;
            if (!this.dept) {
              this.$message({
                type: "error",
                message: "用户无组织机构信息，请联系安伟工作人员！"
              });
            } else {
              let title="出仓单信息";
              let type='add';
              this.$refs.StockOutForm.show({
                title,
                type
              })
            }
          }
        })
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
          this.stockDateRange = [];
          this.search.stockDateStart = '';
          this.search.stockDateEnd = '';
        this.onLoad(this.page);
      },
      searchChange(params, done) {
          this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        handleDatePickerChange(value) {
            if (value) {
                this.search.stockDateStart = value[0];
                this.search.stockDateEnd = value[1];
            } else {
                this.search.stockDateStart = '';
                this.search.stockDateEnd = '';
            }
        },
    }
  };
</script>

<style scoped>
  .row-yellow {
    background-color: rgb(255, 253, 230) !important;
    cursor: pointer;
  }
</style>
